<template>
  <div class="project-management-container">
    <div class="header">
      <div class="title-container">
        <h1 class="page-title">项目管理</h1>
        <p class="page-description">管理系统中的所有项目、版本和产品线信息</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="showCreateProjectDialog">
          <el-icon><Plus /></el-icon>
          创建项目
        </el-button>
      </div>
    </div>
    
    <!-- 统计信息区域 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ productLinesCount }}</div>
              <div class="stat-label">产品线总数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ projectsCount }}</div>
              <div class="stat-label">项目总数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ casesCount }}</div>
              <div class="stat-label">用例总数</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <div class="query-section">
      <el-card>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="选择项目">
              <el-select v-model="selectedProjectId" placeholder="请选择项目" @change="onProjectChange">
                <el-option
                  v-for="project in projects"
                  :key="project.id"
                  :label="project.name"
                  :value="project.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="选择版本">
              <el-select v-model="selectedVersionId" placeholder="请选择版本">
                <el-option
                  v-for="version in filteredVersions"
                  :key="version.id"
                  :label="version.version_number"
                  :value="version.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属产品线">
              <el-select v-model="selectedProductLineId" placeholder="请选择产品线">
                <el-option
                  v-for="line in productLines"
                  :key="line.id"
                  :label="line.name"
                  :value="line.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" style="text-align: right; padding-top: 10px;">
            <el-button type="primary" @click="queryProjects">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="resetQuery">
              <el-icon><RefreshLeft /></el-icon>
              重置
            </el-button>
          </el-col>
        </el-row>
      </el-card>
    </div>
    
    <div class="table-section">
      <el-card>
        <el-table
          v-loading="loading"
          :data="projectListData"
          style="width: 100%"
          border
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="项目ID" width="80">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="name" label="项目名称" min-width="150" />
          <el-table-column prop="version_number" label="当前版本" width="100" />
          <el-table-column prop="project_type" label="项目类型" width="100" />
          <el-table-column prop="product_line_name" label="所属产品线" width="120" />
          <el-table-column prop="description" label="项目描述" min-width="200" show-overflow-tooltip />
          <el-table-column prop="created_at" label="创建时间" width="180">
            <template #default="scope">
              {{ formatTime(scope.row.created_at) }}
            </template>
          </el-table-column>
          <el-table-column prop="updated_at" label="更新时间" width="180">
            <template #default="scope">
              {{ formatTime(scope.row.updated_at) }}
            </template>
          </el-table-column>
          <el-table-column prop="owner" label="负责人" width="100" />
          <el-table-column label="操作" width="240" fixed="right">
            <template #default="scope">
              <el-button link type="primary" @click="handleEdit(scope.row)">
                编辑
              </el-button>
              <el-button link type="info" @click="showVersionDialog(scope.row.id, scope.row.name)">
                版本管理
              </el-button>
              <el-button link type="danger" @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
    
    <!-- 创建项目弹窗 -->
    <el-dialog
      v-model="createProjectDialogVisible"
      title="创建新项目"
      width="600px"
      class="create-project-dialog"
      @close="handleCloseCreateDialog"
    >
      <el-form
        :model="createProjectForm"
        label-width="80px"
      >
        <el-form-item label="项目名称">
          <el-input v-model="createProjectForm.name" placeholder="请输入项目名称" />
        </el-form-item>
        
        <el-form-item label="项目描述">
          <el-input
            v-model="createProjectForm.description"
            type="textarea"
            placeholder="请输入项目描述"
            :rows="3"
          />
        </el-form-item>
        
        <el-form-item label="项目类型">
          <el-select v-model="createProjectForm.project_type" placeholder="请选择项目类型">
            <el-option label="Web应用" value="web" />
            <el-option label="移动应用" value="mobile" />
            <el-option label="API接口" value="api" />
            <el-option label="桌面应用" value="desktop" />
            <el-option label="其他类型" value="other" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="负责人">
          <el-input v-model="createProjectForm.owner" placeholder="请输入负责人姓名" />
        </el-form-item>
        
        <el-form-item label="所属部门">
          <el-input v-model="createProjectForm.department" placeholder="请输入所属部门" />
        </el-form-item>
        
        <el-form-item label="所属产品线" class="no-wrap-label">
          <el-select v-model="createProjectForm.product_line_id" placeholder="请选择所属产品线">
            <el-option
              v-for="line in productLines"
              :key="line.id"
              :label="line.name"
              :value="line.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      
      <div class="dialog-footer">
        <el-button @click="handleCloseCreateDialog">取消</el-button>
        <el-button type="primary" @click="handleCreateProject">创建</el-button>
      </div>
    </el-dialog>
    
    <!-- 编辑项目弹窗 -->
    <el-dialog
      v-model="editProjectDialogVisible"
      title="编辑项目"
      width="600px"
      class="edit-project-dialog"
    >
      <el-form
        :model="editProjectForm"
        label-width="80px"
      >
        <el-form-item label="项目名称">
          <el-input v-model="editProjectForm.name" placeholder="请输入项目名称" />
        </el-form-item>
        
        <el-form-item label="项目描述">
          <el-input
            v-model="editProjectForm.description"
            type="textarea"
            placeholder="请输入项目描述"
            :rows="3"
          />
        </el-form-item>
        
        <el-form-item label="项目类型">
          <el-select v-model="editProjectForm.project_type" placeholder="请选择项目类型">
            <el-option label="Web应用" value="web" />
            <el-option label="移动应用" value="mobile" />
            <el-option label="API接口" value="api" />
            <el-option label="桌面应用" value="desktop" />
            <el-option label="其他类型" value="other" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="负责人">
          <el-input v-model="editProjectForm.owner" placeholder="请输入负责人姓名" />
        </el-form-item>
        
        <el-form-item label="所属部门">
          <el-input v-model="editProjectForm.department" placeholder="请输入所属部门" />
        </el-form-item>
        
        <el-form-item label="所属产品线" class="no-wrap-label">
          <el-select v-model="editProjectForm.product_line_id" placeholder="请选择所属产品线">
            <el-option
              v-for="line in productLines"
              :key="line.id"
              :label="line.name"
              :value="line.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      
      <div class="dialog-footer">
        <el-button @click="editProjectDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEditProject">保存</el-button>
      </div>
    </el-dialog>
    
    <!-- 版本管理弹窗 -->
    <el-dialog
      v-model="versionDialogVisible"
      :title="versionDialogTitle"
      width="800px"
      class="version-management-dialog"
    >
      <div class="version-content">
        <div class="version-form-section">
          <h3>版本信息</h3>
          <el-form
            :model="versionForm"
            label-width="100px"
            size="small"
          >
            <el-form-item label="版本号">
              <el-input v-model="versionForm.version_number" placeholder="请输入版本号（如：1.0.0）" />
            </el-form-item>
            
            <el-form-item label="版本描述">
              <el-input
                v-model="versionForm.description"
                type="textarea"
                placeholder="请输入版本描述"
                :rows="2"
              />
            </el-form-item>
            
            <el-form-item label="发布日期">
              <el-date-picker
                v-model="versionForm.release_date"
                type="date"
                placeholder="选择日期"
                style="width: 100%;"
              />
            </el-form-item>
            
            <el-form-item label="设为当前版本">
              <el-switch v-model="versionForm.is_current" />
            </el-form-item>
          </el-form>
          
          <div style="text-align: right; margin-top: 10px;">
            <el-button type="primary" @click="saveVersion" size="small">
              {{ versionForm.id ? '更新版本' : '添加版本' }}
            </el-button>
          </div>
        </div>
        
        <div class="version-list-section">
          <h3>版本列表</h3>
          <el-table
            v-if="projectVersions.length > 0"
            :data="projectVersions"
            style="width: 100%"
            size="small"
            border
          >
            <el-table-column prop="version_number" label="版本号" width="120" />
            <el-table-column prop="description" label="版本描述" show-overflow-tooltip min-width="200" />
            <el-table-column prop="release_date" label="发布日期" width="120" />
            <el-table-column prop="is_current" label="是否当前版本" width="100">
              <template #default="scope">
                <el-tag v-if="scope.row.is_current" type="success">是</el-tag>
                <span v-else>否</span>
              </template>
            </el-table-column>
            <el-table-column prop="created_at" label="创建时间" width="180">
              <template #default="scope">
                {{ formatTime(scope.row.created_at) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="scope">
                <el-button link type="primary" @click="showEditVersionForm(scope.row)" size="small">
                  编辑
                </el-button>
                <el-button link type="warning" @click="setCurrentVersion(scope.row.id, scope.row.version_number)" size="small">
                  {{ scope.row.is_current ? '已是当前版本' : '设为当前版本' }}
                </el-button>
                <el-button link type="danger" @click="handleDeleteVersion(scope.row.id, scope.row.version_number)" size="small">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div v-else class="no-data">
            <p>暂无版本数据，点击上方按钮添加版本</p>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '../utils/axios'
import { useRoute, useRouter } from 'vue-router'
import type { Project, Version, ProductLine } from '../types'
import { Plus, Search, RefreshLeft } from '@element-plus/icons-vue'

// 路由
const route = useRoute()
const router = useRouter()

// 格式化时间，去掉毫秒部分
const formatTime = (timeString: string) => {
  if (!timeString) return ''
  try {
    const date = new Date(timeString)
    // 格式化成年-月-日 时:分:秒格式，去掉毫秒
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
  } catch (error) {
    console.error('时间格式化失败:', error)
    return timeString // 如果格式化失败，返回原始字符串
  }
}

// 项目列表数据
const projects = ref<Project[]>([])
const versions = ref<Version[]>([])
const productLines = ref<ProductLine[]>([])
const projectListData = ref<Project[]>([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 统计信息
const productLinesCount = ref(0)
const projectsCount = ref(0)
const casesCount = ref(0)

// 查询参数
const selectedProjectId = ref<string>('')
const selectedVersionId = ref<string>('')
const selectedProductLineId = ref<string>('')

// 创建项目相关状态
const createProjectDialogVisible = ref(false)
const createProjectForm = ref({
  name: '',
  description: '',
  project_type: '',
  owner: '', // 负责人，原creator
  department: '',
  product_line_id: ''
})

// 根据选中的项目过滤版本
const filteredVersions = computed(() => {
  if (!selectedProjectId.value) return versions.value
  return versions.value.filter((version: Version) => String(version.project) === String(selectedProjectId.value))
})

// 获取项目列表
    const fetchProjects = async () => {
      try {
        loading.value = true
        const response = await request.get('/api/projects/projects/')
        const rawProjects = response.data.results || response.data
        
        // 去除重复数据，使用Map根据项目名称去重
        const uniqueProjectsMap = new Map<string, Project>()
        rawProjects.forEach((project: Project) => {
          if (!uniqueProjectsMap.has(project.name)) {
            uniqueProjectsMap.set(project.name, project)
          }
        })
        
        // 将Map转回数组
        const projectArray = Array.from(uniqueProjectsMap.values())
        
        // 确保产品线数据已加载完成
        if (productLines.value.length === 0) {
          await fetchProductLines()
        }
        
        // 确保版本数据已加载完成
        if (versions.value.length === 0) {
          await fetchVersions()
        }
        
        console.log('产品线数据:', productLines.value)
        console.log('CaseMaker项目:', projectArray.find(p => p.name === 'CaseMaker'))
        
        // 将项目数据与版本数据关联，为每个项目添加当前版本信息和产品线名称
        const projectsWithVersions = projectArray.map(project => {
          // 查找该项目的版本，使用字符串比较确保类型匹配
          const projectVersions = versions.value.filter(version => 
            String(version.project) === String(project.id)
          )
          
          // 查找该项目的当前版本（is_current为true的版本）
          const currentVersion = projectVersions.find(version => version.is_current)
          
          // 查找产品线名称 - 使用更健壮的比较逻辑
          let productLineName = ''
          
          // 优先使用API返回的product_line_name（如果有）
          if (project.product_line_name) {
            productLineName = project.product_line_name
          } 
          // 否则尝试通过product_line字段关联
          else if (project.product_line) {
            const productLine = productLines.value.find(line => 
              String(line.id) === String(project.product_line)
            )
            if (productLine) {
              productLineName = productLine.name
              console.log(`项目${project.name}关联到产品线: ${productLineName}`)
            }
          }
          
          // 创建关联后的项目对象
          const projectWithInfo = {
            ...project,
            product_line_name: productLineName,
            // 确保将后端的creator字段映射到前端使用的owner字段
            owner: project.creator || project.owner
          }
          
          // 如果找到当前版本，则添加version_number字段
          if (currentVersion) {
            return { ...projectWithInfo, version_number: currentVersion.version_number }
          }
          
          return projectWithInfo
        })
        
        projects.value = projectsWithVersions
        projectsCount.value = projects.value.length
    
    // 如果是从创建项目路由进入，自动打开创建项目弹窗
    if (route.path === '/project/create' || route.name === 'createProject') {
      showCreateProjectDialog()
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
    ElMessage.error('获取项目列表失败')
  } finally {
    loading.value = false
  }
}

// 获取版本列表
const fetchVersions = async () => {
  try {
    const response = await request.get('/api/projects/versions/')
    versions.value = response.data.results || response.data
  } catch (error) {
    console.error('获取版本列表失败:', error)
    ElMessage.error('获取版本列表失败')
  }
}

// 获取产品线列表
const fetchProductLines = async () => {
  try {
    const response = await request.get('/api/projects/product_lines/')
    productLines.value = response.data.results || response.data
    productLinesCount.value = productLines.value.length
  } catch (error) {
    console.log('产品线功能尚未实现，使用模拟数据')
    // 如果后端API不可用，使用模拟数据
    productLines.value = [
      { id: '1', name: '企业应用', description: '企业级应用产品线', created_at: new Date().toISOString(), updated_at: new Date().toISOString() },
      { id: '2', name: '移动应用', description: '移动端应用产品线', created_at: new Date().toISOString(), updated_at: new Date().toISOString() },
      { id: '3', name: '云服务', description: '云计算服务产品线', created_at: new Date().toISOString(), updated_at: new Date().toISOString() }
    ]
    productLinesCount.value = productLines.value.length
  }
}

// 获取用例总数
const fetchCasesCount = async () => {
  try {
    const response = await request.get('/api/cases/test-cases/')
    // 从API响应中获取实际的用例总数
    casesCount.value = response.data.count || response.data.length || 0
  } catch (error) {
    console.error('获取用例总数失败:', error)
    // 如果后端API不可用，尝试从表格数据中获取总数
    casesCount.value = total.value || 0
  }
}

// 查询项目
    const queryProjects = async () => {
      try {
        loading.value = true
        const params: Record<string, any> = {
          page: currentPage.value,
          page_size: pageSize.value
        }
        
        if (selectedProjectId.value) {
          params['project_id'] = selectedProjectId.value
        }
        
        if (selectedVersionId.value) {
          params['version_id'] = selectedVersionId.value
        }
        
        if (selectedProductLineId.value) {
          params['product_line_id'] = selectedProductLineId.value
        }
        
        const response = await request.get('/api/projects/projects/', { params })
        const rawData = response.data.results || response.data
        
        // 去除重复数据，使用Map根据项目名称去重
        const uniqueProjectsMap = new Map<string, Project>()
        rawData.forEach((project: Project) => {
          if (!uniqueProjectsMap.has(project.name)) {
            uniqueProjectsMap.set(project.name, project)
          }
        })
        
        // 将Map转回数组
        const projects = Array.from(uniqueProjectsMap.values())
        
        // 确保产品线数据已加载完成
        if (productLines.value.length === 0) {
          await fetchProductLines()
        }
        
        // 确保版本数据已加载完成
        if (versions.value.length === 0) {
          await fetchVersions()
        }
        
        // 将项目数据与版本数据关联，为每个项目添加当前版本信息和产品线名称
        const projectsWithVersions = projects.map(project => {
          // 查找该项目的版本，使用字符串比较确保类型匹配
          const projectVersions = versions.value.filter(version => 
            String(version.project) === String(project.id)
          )
          
          // 查找该项目的当前版本（is_current为true的版本）
          const currentVersion = projectVersions.find(version => version.is_current)
          
          // 查找产品线名称 - 使用更健壮的比较逻辑
          let productLineName = ''
          
          // 优先使用API返回的product_line_name（如果有）
          if (project.product_line_name) {
            productLineName = project.product_line_name
          } 
          // 否则尝试通过product_line字段关联
          else if (project.product_line) {
            const productLine = productLines.value.find(line => 
              String(line.id) === String(project.product_line)
            )
            if (productLine) {
              productLineName = productLine.name
            }
          }
          
          // 创建关联后的项目对象
          const projectWithInfo = {
            ...project,
            product_line_name: productLineName,
            // 确保将后端的creator字段映射到前端使用的owner字段
            owner: project.creator || project.owner
          }
          
          // 如果找到当前版本，则添加version_number字段
          if (currentVersion) {
            return { ...projectWithInfo, version_number: currentVersion.version_number }
          }
          
          return projectWithInfo
        })
        
        projectListData.value = projectsWithVersions
        total.value = projectListData.value.length
  } catch (error) {
    console.error('查询项目失败:', error)
    ElMessage.error('查询项目失败')
  } finally {
    loading.value = false
  }
}

// 重置查询
const resetQuery = () => {
  selectedProjectId.value = ''
  selectedVersionId.value = ''
  selectedProductLineId.value = ''
  currentPage.value = 1
  pageSize.value = 10
  queryProjects()
}

// 处理项目变更
const onProjectChange = () => {
  selectedVersionId.value = ''
}

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  queryProjects()
}

// 处理当前页变化
const handleCurrentChange = (current: number) => {
  currentPage.value = current
  queryProjects()
}

// 编辑项目相关状态
const editProjectDialogVisible = ref(false)
const editProjectForm = ref({
  id: '',
  name: '',
  description: '',
  project_type: '',
  owner: '',
  department: '',
  product_line_id: ''
})

// 版本管理相关状态
const versionDialogVisible = ref(false)
const versionDialogTitle = ref('')
const versionForm = ref({
  id: '',
  project_id: '',
  version_number: '',
  description: '',
  release_date: '',
  is_current: false
})
const projectVersions = ref<Version[]>([])
const currentProjectId = ref('')

// 处理编辑
const handleEdit = (row: Project) => {
  editProjectForm.value = {
    id: row.id,
    name: row.name,
    description: row.description,
    project_type: row.project_type,
    owner: row.owner,
    department: row.department,
    // 优先使用product_line字段，这是后端实际存储的字段
    product_line_id: row.product_line || row.product_line_id || ''
  }
  editProjectDialogVisible.value = true
}

// 保存编辑
const saveEditProject = async () => {
  try {
    // 构建正确的请求数据格式，确保使用后端期望的字段名
    const projectData = {
      ...editProjectForm.value,
      // 确保使用product_line而不是product_line_id
      product_line: editProjectForm.value.product_line_id,
      // 负责人字段前端使用owner，但后端实际使用creator
      creator: editProjectForm.value.owner
    }
    
    // 使用类型断言和条件删除
    if ('product_line_id' in projectData) {
      delete (projectData as any).product_line_id;
    }
    if ('owner' in projectData) {
      delete (projectData as any).owner;
    }
    
    const response = await request.put(`/api/projects/projects/${editProjectForm.value.id}/`, projectData)
    
    if (response.status === 200) {
      ElMessage.success('项目更新成功！')
      editProjectDialogVisible.value = false
      
      // 重新获取项目列表以确保数据最新
      await fetchProjects()
      await queryProjects()
    }
  } catch (error) {
    console.error('更新项目失败:', error)
    ElMessage.error('更新项目失败，请重试')
  }
}

// 处理删除
const handleDelete = (row: Project) => {
  ElMessageBox.confirm(
    `确定要删除项目「${row.name}」吗？此操作不可撤销。`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await request.delete(`/api/projects/projects/${row.id}/`)
      
      if (response.status === 204) {
        ElMessage.success('项目删除成功！')
        
        // 重新获取项目列表
        fetchProjects()
        queryProjects()
      }
    } catch (error) {
      console.error('删除项目失败:', error)
      ElMessage.error('删除项目失败，请重试')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 显示创建项目弹窗
const showCreateProjectDialog = () => {
  createProjectForm.value = {
    name: '',
    description: '',
    project_type: '',
    owner: '',
    department: '',
    product_line_id: ''
  }
  createProjectDialogVisible.value = true
}

// 创建项目
const handleCreateProject = async () => {
  try {
    const response = await request.post('/api/projects/projects/', createProjectForm.value)
    
    if (response.status === 201) {
      ElMessage.success('项目创建成功！')
      createProjectDialogVisible.value = false
      
      // 重新获取项目列表
      fetchProjects()
      
      // 如果是从创建项目路由进入，创建成功后跳转到项目列表
      if (route.path === '/project/create' || route.name === 'createProject') {
        router.push('/project')
      }
    }
  } catch (error) {
    console.error('创建项目失败:', error)
    ElMessage.error('创建项目失败，请重试')
  }
}

// 关闭创建项目弹窗
const handleCloseCreateDialog = () => {
  createProjectDialogVisible.value = false
  
  // 如果是从创建项目路由进入，关闭弹窗后也跳转到项目列表
  if (route.path === '/project/create' || route.name === 'createProject') {
    router.push('/project')
  }
}

// 显示版本管理弹窗
const showVersionDialog = (projectId: string, projectName: string) => {
  currentProjectId.value = projectId
  versionDialogTitle.value = `${projectName} - 版本管理`
  fetchProjectVersions(projectId)
  versionDialogVisible.value = true
}

// 获取项目版本列表
const fetchProjectVersions = async (projectId: string) => {
  try {
    const response = await request.get(`/api/projects/versions/?project=${projectId}`)
    projectVersions.value = response.data.results || response.data
  } catch (error) {
    console.error('获取项目版本失败:', error)
    ElMessage.error('获取项目版本失败')
  }
}

// 显示添加版本表单
const showAddVersionForm = () => {
  versionForm.value = {
    id: '',
    project_id: currentProjectId.value,
    version_number: '',
    description: '',
    release_date: '',
    is_current: false
  }
}

// 显示编辑版本表单
const showEditVersionForm = (version: Version) => {
  versionForm.value = {
    id: version.id,
    project_id: version.project_id,
    version_number: version.version_number,
    description: version.description || '',
    release_date: version.release_date ? new Date(version.release_date).toISOString().split('T')[0] : '',
    is_current: version.is_current || false
  }
}

// 保存版本
const saveVersion = async () => {
  try {
    // 验证必填字段
    if (!versionForm.value.version_number) {
      ElMessage.error('请输入版本号')
      return
    }
    
    if (!currentProjectId.value) {
      ElMessage.error('项目ID不存在')
      return
    }
    
    // 只创建后端需要的字段，避免发送不必要的字段
    const versionData = {
      project: currentProjectId.value,
      version_number: versionForm.value.version_number,
      description: versionForm.value.description || '',
      is_current: versionForm.value.is_current || false
    }
    
    // 只有当release_date有值时才添加这个字段
    if (versionForm.value.release_date) {
      // 确保日期格式为YYYY-MM-DD
      try {
        const date = new Date(versionForm.value.release_date as string);
        // 转换为YYYY-MM-DD格式
        (versionData as any).release_date = date.toISOString().split('T')[0];
      } catch (error) {
        ElMessage.error('日期格式不正确，请使用YYYY-MM-DD格式');
        return;
      }
    }
    
    let response
    
    if (versionForm.value.id) {
      // 编辑版本
      response = await request.put(`/api/projects/versions/${versionForm.value.id}/`, versionData)
    } else {
      // 添加版本
      response = await request.post('/api/projects/versions/', versionData)
    }
    
    if (response.status === 200 || response.status === 201) {
      ElMessage.success(versionForm.value.id ? '版本更新成功！' : '版本添加成功！')
      showAddVersionForm()
      fetchProjectVersions(currentProjectId.value)
      fetchVersions()
      // 刷新项目列表数据，确保当前版本字段更新
      fetchProjects()
      queryProjects()
    }
  } catch (error: any) {
    // 增强错误处理，显示更详细的错误信息
    if (error.response && error.response.data) {
      let errorMsg = '保存版本失败'
      if (error.response.data.message) {
        errorMsg = `保存版本失败：${error.response.data.message}`
      } else if (error.response.data.detail) {
        errorMsg = `保存版本失败：${error.response.data.detail}`
      } else if (typeof error.response.data === 'object') {
        // 尝试解析验证错误
        const errorDetails = Object.entries(error.response.data)
          .map(([field, msgs]) => `${field}: ${msgs}`)
          .join('\n')
        errorMsg = `保存版本失败：\n${errorDetails}`
      }
      ElMessage.error(errorMsg)
    } else {
      ElMessage.error('保存版本失败，请重试')
    }
  }
}

// 处理删除版本
const handleDeleteVersion = async (versionId: string, versionNumber: string) => {
  ElMessageBox.confirm(
    `确定要删除版本「${versionNumber}」吗？此操作不可撤销。`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await request.delete(`/api/projects/versions/${versionId}/`)
      
      if (response.status === 204) {
        ElMessage.success('版本删除成功！')
        fetchProjectVersions(currentProjectId.value)
        fetchVersions()
      }
    } catch (error: any) {
      ElMessage.error('删除版本失败，请重试')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 设置当前版本
const setCurrentVersion = async (versionId: string, versionNumber: string) => {
  ElMessageBox.confirm(
    `确定要将「${versionNumber}」设置为当前版本吗？`,
    '确认设置',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(async () => {
    try {
      const response = await request.post(`/api/projects/versions/${versionId}/set-current/`)
      
      if (response.status === 200) {
        ElMessage.success('当前版本设置成功！')
        fetchProjectVersions(currentProjectId.value)
        fetchVersions()
      }
    } catch (error) {
      console.error('设置当前版本失败:', error)
      ElMessage.error('设置当前版本失败，请重试')
    }
  }).catch(() => {
    ElMessage.info('已取消设置')
  })
}

// 组件挂载时加载数据
onMounted(async () => {
  // 确保版本数据先加载完成
  await fetchVersions()
  
  // 然后再加载和查询项目数据
  await Promise.all([
    fetchProjects(),
    fetchProductLines(),
    fetchCasesCount()
  ])
  
  // 最后查询项目列表
  queryProjects()
})
</script>

<style scoped>
.project-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title-container {
  text-align: center;
}

/* 统一标题样式已在全局style.css中定义 */
.header .page-title {
  text-align: center;
}

.page-description {
  font-size: 14px;
  color: #606266;
  margin-top: 8px;
  text-align: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

/* 统计信息区域样式 */
.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 8px;
  overflow: hidden;
}

.stat-content {
  padding: 20px;
  text-align: center;
}

.stat-number {
  font-size: 36px;
  font-weight: bold;
  margin-bottom: 10px;
}

.stat-label {
  font-size: 16px;
  opacity: 0.9;
}

.query-section {
  margin-bottom: 20px;
}

.table-section {
  background-color: white;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.cases-count {
  color: #409eff;
  font-weight: bold;
}

.create-project-dialog .el-form-item {
  margin-bottom: 20px;
}

.create-project-dialog .no-wrap-label .el-form-item__label {
  white-space: nowrap;
  width: auto !important;
}

.create-project-dialog .dialog-footer {
  margin-top: 20px;
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .project-management-container {
    padding: 10px;
  }
  
  .stats-section .el-row {
    display: flex;
    flex-direction: column;
  }
  
  .stats-section .el-col {
    width: 100% !important;
    margin-bottom: 10px;
  }
  
  .query-section .el-row {
    display: flex;
    flex-direction: column;
  }
  
  .query-section .el-col {
    width: 100% !important;
    margin-bottom: 10px;
  }
  
  .query-section .el-col:last-child {
    text-align: left;
    margin-top: 10px;
  }
  
  .pagination-container {
    text-align: center;
  }
}

/* 版本管理相关样式 */
.version-management-dialog .version-content {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.version-form-section {
  flex: 1;
  min-width: 300px;
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.version-list-section {
  flex: 2;
  min-width: 400px;
}

.version-content h3 {
  font-size: 16px;
  margin-bottom: 15px;
  color: #303133;
}

.no-data {
  text-align: center;
  padding: 40px;
  color: #909399;
}

/* 编辑项目弹窗样式 */
.edit-project-dialog .el-form-item {
  margin-bottom: 20px;
}

.edit-project-dialog .no-wrap-label .el-form-item__label {
  white-space: nowrap;
  width: auto !important;
}

.edit-project-dialog .dialog-footer {
  margin-top: 20px;
  text-align: right;
}
</style>